<?php

namespace App\Http\Controllers\Api;

use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cache;

class WechatController extends Controller
{
    public function miniLogin(Request $request)
    {
        $code = $request->input('code');
        $app = app('wechat.mini_program');
        $user = $app->auth->session($code);
        // 使用 Linux 服务器生成 168 位随机字符串
        $cache_key = shell_exec('head -n 80 /dev/urandom | tr -dc A-Za-z0-9 | head -c 168');
        $cache_value = [
            'openid' => $user['openid'],
        ];
        $expiresAt = Carbon::now()->addDays(7);
        Cache::put($cache_key, json_encode($cache_value), $expiresAt);
        return response()->json([
            'status' => 'success',
            'code' => 1,
            'data' => $cache_key
        ]);
    }

    public function checkToken(Request $request)
    {
        $token = $request->input('token');
        $cache = Cache::get($token);
        if (!$cache) {
            return response()->json([
                'status' => 'success',
                'code' => 0,
                'msg' => 'token已过期，请重新获取',
            ]);
        }
        return response()->json([
            'status' => 'success',
            'code' => 1,
        ]);
    }

    public function test()
    {
        $openid = 'omC1s5dTg-Pf5hxbZ19RRol_Iwu4';
        $app = app('wechat.mini_program');
        $user = $app->user->get($openid);
        dd($user);
    }
}
